//
//  SHSearchViewController.m
//  UI_CarHome
//
//  Created by dllo on 15/11/2.
//  Copyright (c) 2015年 沈浩. All rights reserved.
//

#import "SHSearchViewController.h"
#import "SHHandle.h"
#import "SHModel.h"
#import "SHSearDetailController.h"
#import "SHSearchTableCell.h"
@interface SHSearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)NSMutableArray *listArr;
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UILabel *label;
@property(nonatomic, retain)UILabel *noSearchLabel;
@property(nonatomic, assign)BOOL isMoreData;


@end

@implementation SHSearchViewController
- (void)dealloc
{
    [_noSearchLabel release];
    [_tableView release];
    [_searchBar release];
    [_listArr release];
    [_label release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.listArr = [NSMutableArray array];
    
    [self createTableView];
    [self createSearchBar];
    
}


#pragma mark --searchBar
- (void)createSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 260, 40)];
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索";
    self.searchBar.barStyle = UIBarMetricsCompact;
    self.searchBar.tintColor = NEWBLUE;
    self.searchBar.translucent = YES;
    self.searchBar.showsSearchResultsButton = YES;
    self.searchBar.searchTextPositionAdjustment = UIOffsetMake(30, 0);
    [_searchBar release];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *searchStr = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strUrl = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.9.5/sou/series.ashx?pm=2&kw=%@&app=2&platform=2&version=4.9.5&deviceid=352246064016861", searchStr];
    [self createDataWithUrl:strUrl];
}

#pragma mark --处理数据
- (void)createDataWithUrl:(NSString *)strUrL {
    if (self.noSearchLabel) {
        [self.noSearchLabel removeFromSuperview];
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strUrL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        
        self.listArr = [SHModel baseModelByArr:dic[@"result"][@"list"]];
       
        if (self.listArr.count == 0) {
            self.noSearchLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -64, WIDTH, HEIGHT)];
            self.noSearchLabel.backgroundColor = [UIColor whiteColor];
            self.noSearchLabel.text = @"抱歉:没有搜索到数据!";
            self.noSearchLabel.textAlignment = NSTextAlignmentCenter;
            [self.tableView addSubview:self.noSearchLabel];
            [_noSearchLabel release];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark 分区
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.listArr.count == 0) {
        
        return nil;
    } else {
        NSString *str = [NSString stringWithFormat:@"共有%ld的搜索结果", self.listArr.count];
        return str;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}



#pragma mark --tableView
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 60;
    // 隐藏cell分割线
    self.tableView.separatorStyle = NO;
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.listArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    SHSearchTableCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[SHSearchTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    SHModel *model = self.listArr[indexPath.row];
    // 关键字高亮
    NSString *keyword = self.searchBar.text;
    // 清除空格
    keyword = [keyword stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    // 设置标签文字
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:model.name];
    // 获取标红的位置和长度
    NSRange range = [model.name rangeOfString:keyword];
    // 设置标签文字的属性
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:20]} range:range];
    cell.titleLabel.text = model.name;
    // 显示在titleLabel上
    cell.titleLabel.attributedText = attrituteString;
    
    
    return cell;
}

#pragma mark --cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPat  {
    SHSearDetailController *seaDetail = [[SHSearDetailController alloc] init];
    [self.navigationController pushViewController:seaDetail animated:YES];
    [seaDetail release];
    SHModel *model = self.listArr[indexPat.row];
    NSString *tableTittle = [model.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strUrl = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov5.0.0/sou/search.ashx?a=2&pm=1&v=5.0.0&q=%@&p=1&s=20&c=210200&cn=%E5%A4%A7%E8%BF%9E&deviceid=8a072a52160706149308539ee6dfb6ca8d6bcf63&issug=0", tableTittle];
    seaDetail.webStr = strUrl;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
